package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.example.demo.security.UserService;
import com.example.demo.util.MD5Util;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	
//    @Autowired
//    private CustomAuthenticationFailureHandler failureHandler;
//
//    @Autowired
//    private CustomAuthenticationSuccessHandler successHandler;
//
//    @Autowired
//    private CustomLogoutSuccessHandler logoutSuccessHandler;
//
//    @Autowired
//    private CustomUserDetailsService userDetailsService;
//
//    @Autowired
//    private JWTAuthenticationFilter jwtAuthenticationFilter;
//    
//    @Bean
//    public PasswordEncoder passwordEncoder() {
//        return new BCryptPasswordEncoder();
//    }
	
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//    	auth.inMemoryAuthentication().withUser("root").password("123456").roles("admin");
////        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
//    }
	
	@Bean
	UserDetailsService UserService() {
		return new UserService();
	}
	

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		/**对于数据库密码不加密的情况*/
		//auth.userDetailsService(customUserService()); 
		
		/**对于数据库密码加密的情况*/
		auth.userDetailsService(UserService()).passwordEncoder(new PasswordEncoder(){
			//rawPassword 前台传递来的 password
			//encodedPassword 后台计算的 password
			@Override
			public String encode(CharSequence rawPassword) {
				return MD5Util.encode((String)rawPassword);
			}
 
			@Override
			public boolean matches(CharSequence rawPassword, String encodedPassword) {
				 return encodedPassword.equals(MD5Util.encode((String)rawPassword));
			}
			
		});
	}
	
	@Override
    protected void configure(HttpSecurity http) throws Exception {
		//http.formLogin()//表单方式
		http.httpBasic()//httpBasic方式
			.and()
			.csrf().disable()
			.authorizeRequests()//授权配置
			.anyRequest()//所有请求
			.authenticated();//需要认证
	}
	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers(
                "/v2/api-docs");
	}
	
}
